package lt.marsrutai.mobile.android.fragment;

import java.util.List;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.RunStopsIntentHolder;
import lt.marsrutai.mobile.android.adapter.RunStopAdapter;
import lt.marsrutai.mobile.android.exception.DataAccessException;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import lt.marsrutai.mobile.android.model.ArrivalTime;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import com.actionbarsherlock.app.SherlockListFragment;


public class RunStopsFragment extends SherlockListFragment {

    private ActivityManager manager;

    private List<ArrivalTime> stops;
    private ArrayAdapter<ArrivalTime> adapter;
    private Runnable downloadTask;

    private String scopeFolder;
    private String runId;
    private String stopId;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_fragment, null);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        manager = new ActivityManager(getActivity());
        manager.showDownloadLoadingBar();

        receiveItemData();

        adapter = new RunStopAdapter(getActivity(), runId, stopId);
        setListAdapter(adapter);

        downloadData();
    }


    public void receiveItemData() {
        RunStopsIntentHolder intentHolder = new RunStopsIntentHolder(getArguments());
        scopeFolder = intentHolder.getScopeFolder();      
        runId = intentHolder.getRunId();      
        stopId = intentHolder.getStopId();
    }

    public void downloadData() {
        downloadTask = new Runnable() {

            @Override
            public void run() {
                getRunStops(scopeFolder, runId);
            }
        };
        Thread thread = new Thread(downloadTask);
        thread.start();
    }

    private void getRunStops(String scopeName, String runId) {
        try {
            stops = AppContext.getDataService().getRunStops(scopeName, runId);
        }
        catch (DataAccessException e) {
            manager.runOnUiThread(manager.errorRes);
            return;
        }
        manager.runOnUiThread(returnRes);
    }

    private final Runnable returnRes = new Runnable() {

        @Override
        public void run() {
            if (stops != null && stops.size() > 0) {
                for (int i = 0; i < stops.size(); i++) {
                    adapter.add(stops.get(i));
                }
            }
            manager.dismissDownloadLoadingBar();
        }
    };

}
